package com.lms.netty.rpc.consumer;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import java.util.concurrent.*;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-06-19 17:34
 * @Description:
 */
public class RpcNettyClient {


    private static ThreadPoolExecutor executor=new ThreadPoolExecutor(1,2,30, TimeUnit.SECONDS,new ArrayBlockingQueue<>(4));
    private static ThreadPoolExecutor executor2=new ThreadPoolExecutor(1, 2, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), new ThreadFactory() {
        private  int count;
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(Thread.currentThread().getThreadGroup(), r, "MyThread-group-" + (++count));
            return thread;
        }
    });

    private static RpcNettyClientHandler clientHandler;

    private static void initClient() {
        clientHandler = new RpcNettyClientHandler();
        NioEventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringDecoder())
                                    .addLast(new StringEncoder())
                                    .addLast(clientHandler);
                        }
                    });
            ChannelFuture sync = bootstrap.connect("127.0.0.1",8090).sync();
            System.out.println("客户端启动...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public Object getBean(final Class<?> className,final String providerName){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{className}, (proxy, method, args) -> {
           if (clientHandler==null){
               initClient();
           }
           clientHandler.setParam(providerName+args[0]);
            System.out.println("代理。。。");
            return executor2.submit(clientHandler).get();
        });

    }

}
